//app.js
//添加事件结束

if (Promise.prototype.finally) {
  console.info("有finally方法!");
} else {
  Promise.prototype.finally = function (callback) {
    var Promise = this.constructor;
    return this.then(
      function (value) {
        Promise.resolve(callback()).then(
          function () {
            return value;
          }
        );
      },
      function (reason) {
        Promise.resolve(callback()).then(
          function () {
            throw reason;
          }
        );
      }
    );
  }
}


App({
  // 设置监听器
  watch: function (ctx, obj) {
    Object.keys(obj).forEach(key => {
      this.observer(ctx.data, key, ctx.data[key], function (value) {
        obj[key].call(ctx, value)
      })
    })
  },
  // 监听属性，并执行监听函数
  observer: function (data, key, val, fn) {
    Object.defineProperty(data, key, {
      configurable: true,
      enumerable: true,
      get: function () {
        return val
      },
      set: function (newVal) {
        if (newVal === val) return
        fn && fn(newVal)
        val = newVal
      },
    })
  },
  onLaunch: function () {

    if (!wx.cloud) {
      console.error('请使用 2.2.3 或以上的基础库以使用云能力')
    } else {
      //this.initCloud();
    }
    this.globalData = {}

    var self = this;
    // 检测新版本
    const updateManager = wx.getUpdateManager()
    updateManager.onUpdateReady(function () {
      wx.showModal({
        title: '更新提示',
        content: '新版本已经准备好，是否重启应用？',
        success(res) {
          if (res.confirm) {
            // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
            updateManager.applyUpdate()
          }
        }
      })
    })
    /**
     * 初次加载判断网络情况
     * 无网络状态下根据实际情况进行调整
     */
    wx.getNetworkType({
      success(res) {
        const networkType = res.networkType
        if (networkType === 'none') {
          self.globalData.isConnected = false
          wx.showToast({
            title: '当前无网络',
            icon: 'loading',
            duration: 2000
          })
        }
      }
    });



    wx.getSystemInfo({
      success: e => {
        this.globalData.StatusBar = e.statusBarHeight;
        let capsule = wx.getMenuButtonBoundingClientRect();
        if (capsule) {
          this.globalData.Custom = capsule;
          this.globalData.CustomBar = capsule.bottom + capsule.top - e.statusBarHeight;
        } else {
          this.globalData.CustomBar = e.statusBarHeight + 50;
        }
      }
    })

  },
  initCloud() {
    wx.cloud.init({
      env: 'demo-0gu0ufac45cd412c',
      traceUser: true,
    })
  },
  // 设置监听器
  watch: function (ctx, obj) {
    Object.keys(obj).forEach(key => {
      this.observer(ctx.data, key, ctx.data[key], function (value) {
        obj[key].call(ctx, value)
      })
    })
  },
  // 监听属性，并执行监听函数
  observer: function (data, key, val, fn) {
    Object.defineProperty(data, key, {
      configurable: true,
      enumerable: true,
      get: function () {
        return val
      },
      set: function (newVal) {
        if (newVal === val) return
        fn && fn(newVal)
        val = newVal
      },
    })
  },
  postRequestBasic: function (remoteUrl, params, backFunction) {
    var self = this;
    var tempurl = self.url + remoteUrl;
    params.tenant = this.tenant;
    var handler = new Promise(function (resolve, reject) {
      wx.request({
        url: tempurl,
        data: params,
        method: "POST",
        header: {
          'content-type': 'application/x-www-form-urlencoded'
        },
        success: function (res) {
          if (res.statusCode == 200) {
            resolve(res.data);
          } else {
            reject("获取数据失败");
          }
        },
        fail: function (res) {
          reject("请检查网络");
        }
      })
    });
    handler.then(backFunction, function (res) {
        self.showModal(res);
      })
      .catch(function (res) {});
    handler.finally(function () {
      wx.hideLoading();
    });
  },
  postRequest: function (remoteUrl, params, backFunction) {
    var self = this;
    if (self.openId) {
      params.openId = this.openId;
    }
    if (self.userToken) {

      params.userToken = self.userToken;
      self.postRequestBasic(remoteUrl, params, backFunction);
    } else {
      if (params.needLogin == null) {
        params.needLogin = self.needLogin;
      }

      if (params.needLogin) {
        //没有userToken
        var promise1 = new Promise(function (resolve, reject) {
          wx.login({
            success(res) {
              console.info(res);
              if (res.code) {
                console.info("没有登录:" + res.code);
                var tempParams = {};
                tempParams.type = self.tenantKey;
                tempParams.code = res.code;
                self.postRequestBasic("/rest/saas_user/loginOauth.htm", tempParams, function (resBack) {
                  if (resBack.userToken) {
                    resolve(resBack)
                  }
                });
                //发起网络请求          
              } else {
                console.log('登录失败！' + res.errMsg)
              }
            }
          })
        });
        promise1.then(res => {
          if (res.code == 0) {
            params.userToken = res.userToken;
            self.userToken = res.userToken;
            self.openId = res.openId;
            self.postRequestBasic(remoteUrl, params, backFunction);
          } else {
            console.info(res);
          }
        });
        console.info("没有登录");
      } else {
        self.postRequestBasic(remoteUrl, params, backFunction);
      }


    }

  },
  postJson: function (remoteUrl, params, backFunction) {
    var self = this;
    if (self.userToken) {
      params.userToken = self.userToken;
    }
    if (this.openId) {
      params.openId = this.openId;
    }
    params.tenant = this.tenant;
    console.log(params)
    var tempurl = self.url + remoteUrl;
    wx.request({
      url: tempurl,
      data: params,
      method: "POST",
      success: function (res) {
        if (res.statusCode == 200) {
          backFunction(res.data);
        }
      }
    })
  },
  postRequestLoading: function (remoteUrl, params, backFunction) {
    wx.showLoading({
      title: '数据加载中',
      mask: true
    })

    this.postRequest(remoteUrl, params, function (res) {
      wx.hideLoading();
      backFunction(res);
    });
  },
  postRequestBasicLoading: function (remoteUrl, params, backFunction) {
    wx.showLoading({
      title: '数据加载中',
      mask: true
    })
    this.postRequestBasic(remoteUrl, params, function (res) {
      backFunction(res);
    });
  },
  postJsonLoading: function (remoteUrl, params, backFunction) {
    this.postJson(remoteUrl, params, function (res) {
      wx.hideLoading();
      backFunction(res);
    });
  },
  getRad: function (d) {
    var PI = Math.PI;
    return d * PI / 180.0;
  },
  getDistance: function (lat1, lng1, lat2, lng2) {
    var f = this.getRad((lat1 + lat2) / 2);
    var g = this.getRad((lat1 - lat2) / 2);
    var l = this.getRad((lng1 - lng2) / 2);
    var sg = Math.sin(g);
    var sl = Math.sin(l);
    var sf = Math.sin(f);
    var s, c, w, r, d, h1, h2;
    var a = 6378137.0; //The Radius of eath in meter.
    var fl = 1 / 298.257;
    sg = sg * sg;
    sl = sl * sl;
    sf = sf * sf;
    s = sg * (1 - sl) + (1 - sf) * sl;
    c = (1 - sg) * (1 - sl) + sf * sl;
    w = Math.atan(Math.sqrt(s / c));
    r = Math.sqrt(s * c) / w;
    d = 2 * w * a;
    h1 = (3 * r - 1) / 2 / c;
    h2 = (3 * r + 1) / 2 / s;
    s = d * (1 + fl * (h1 * sf * (1 - sg) - h2 * (1 - sf) * sg));
    //s = s / 1000;
    s = s.toFixed(2); //指定小数点后的位数。
    return s;
  },
  distance(lat1, lng1, lat2, lng2) {
    var result = this.getDistance(lat1, lng1, lat2, lng2);
    console.info(result);
    if (isNaN(result)) {
      return -1;
    }
    if (result > 1000) {
      result = result / 1000;
      result = result.toFixed(0);
      return result + "km"
    } else {
      return result.toFixed(0) + "m"
    }
  },
  // 微信支付
  pay: function (payinfo, handle, callback) {
    // wx.showLoading({
    //   title: '数据加载中',
    // })
    console.log(payinfo);
    wx.requestPayment({
      timeStamp: payinfo.timestamp,
      nonceStr: payinfo.noncestr,
      package: payinfo.packageInfo,
      signType: payinfo.signType,
      paySign: payinfo.sign,
      success: function (r) {
        console.log(r)
        wx.hideLoading();
        wx.showModal({
          title: '提示',
          content: '支付成功',
          showCancel: false,
          success: function (res) {
            if (res.confirm) {
              if (handle) {
                handle();
              }
            }
          }
        })
      },
      fail: function (r) {
        wx.hideLoading();
        wx.showModal({
          title: '提示',
          content: '支付失败',
          showCancel: false,
          success: function (res) {
            if (callback) {
              callback();
            }
          }
        })
      }
    })
  },
  showModal(msg, callback) {
    wx.showModal({
      title: '提示',
      content: msg,
      showCancel: false,
      success: function (res) {
        if (callback) {
          callback();
        }
      }
    })
  },
  showToast(title) {
    wx.showToast({
      title: title,
      icon: 'success',
      duration: 2000,
      success: function () {

      }
    })
  },
  setNavigationBarTitle(title) {
    wx.setNavigationBarTitle({
      title: '' + title
    })
  },
  setStorage: function (key, value) {
    wx.setStorage({
      key: key,
      data: value
    })
  },
  // 获取缓存内容
  getStorage: function (key, callback = () => {}) {
    wx.getStorage({
      key: key,
      success(res) {
        console.log(res);
        callback(res.data)
      }
    })
  },
  // 删除缓存内容
  removeStorage: function (key) {
    wx.removeStorage({
      key
    })
  },
  getShareUser() {
    if (this.shareUser) {
      console.info("别人分享");
      return this.shareUser;
    } else {
      console.info("自我分享");
      return this.user.id;
    }
  },
  request: function (remoteUrl, params, response) {
    self.dataRequest(remoteUrl, params, response.target, response.modelKey, response.callback);
  },

  dataRequest: function (remoteUrl, params, target, modelKey, callback) {

    var self = this;
    var tempurl = self.url + remoteUrl;
    if (this.tenant) {
      params.tenant = this.tenant;
    }
    if (this.openId) {
      params.openId = this.openId;
    }


    if (this.userToken) {
      params.userToken = this.userToken;
    } else {
      if (params.needLogin == null) {
        params.needLogin = self.needLogin;
      }
      if (params.needLogin) {
        wx.login({
          success(res) {
            console.info(res);
            if (res.code) {
              var tempParams = {};
              tempParams.type = self.tenantKey;
              tempParams.code = res.code;
              if (self.tenant) {
                tempParams.tenant = self.tenant;
              }
              self.postData(self.url + "/rest/saas_user/loginOauth.htm", tempParams, function (resBack) {
                if (resBack.code == 0) {
                  if (resBack.userToken) {
                    self.userToken = resBack.userToken;
                    params.userToken = resBack.userToken;
                  }
                  if (resBack.openId) {
                    self.openId = resBack.openId;
                  }
                  self.initData(tempurl, params, target, modelKey, callback);

                }
              });
              console.info("没有登录:" + res.code);
              //发起网络请求          
            } else {
              console.log('登录失败！' + res.errMsg)
            }
          }
        })
        return;
      }
    }
    self.initData(tempurl, params, target, modelKey, callback)

  },
  loadMore(remoteUrl, params, target, modelKey, callback) {
    var self = this;
    var tempurl = self.url + remoteUrl;
    if (this.tenant) {
      params.tenant = this.tenant;
    }
    if (this.userToken) {
      params.userToken = this.userToken;
    }
    self.initMore(tempurl, params, target, modelKey, callback)

  },
  initData(remoteUrl, params, target, modelKey, callback) {
    this.postData(remoteUrl, params, function (obj) {
      if (obj.code == 0) {
        var datas = {};
        //datas["loading"]=false;
        if (obj.list) {
          target.totalPage = obj.totalPage;
          datas[modelKey] = obj.list
          target.setData(datas);

          var page = {};
          page.total = obj.total;
          target.setData(page);
        } else {
          datas[modelKey] = obj
          target.setData(datas);
        }
      }
      if (callback) {
        var func = callback.bind(target);
        func(obj);
      }
      wx.stopPullDownRefresh();

    });

  },
  initMore(remoteUrl, params, target, modelKey, callback) {
    this.postData(remoteUrl, params, function (obj) {
      if (obj.code == 0) {
        var datas = {};
        if (obj.list) {
          target.totalPage = obj.totalPage;

          var dataList = target.data[modelKey].concat(obj.list);
          datas[modelKey] = dataList;
          target.setData(datas);
          var page = {};
          page.total = obj.total;
          target.setData(page);
        } else {
          datas[modelKey] = obj
          target.setData(datas);
        }
      }
      if (callback) {
        var func = callback.bind(target);
        func(obj);
      }

    });

  },
  postData: function (remoteUrl, params, callback) {

    if (params.contentType) {
      //'application/json'
    } else {
      params.contentType = "application/x-www-form-urlencoded";
    }

    if (params.method) {
      //GET POST
    } else {
      params.method = "POST";
    }


    wx.request({
      url: remoteUrl,
      data: params,
      method: params.method,
      header: {
        'content-type': params.contentType
      },
      success: function (res) {
        if (res.statusCode == 200) {
          callback(res.data);
        } else {

        }
      },
      fail: function (res) {

      }
    })
  },
  isEmpty(str) {
    if (str == "" || str == null) {
      return true;
    }
    return false;
  },
  handleError(res) {
    if (res.code == 404) {

    }
  },
  url: 'https://nbmall.nbsaas.com',
  url1: 'http://localhost:8080/web',
  url2: 'https://cloud.newbyte.ltd',

  userInfo: {},
  tenantKey: "wxapp",
  size: 10,
  longitude: '',
  latitude: '',
  needLogin: false,
  tenant: 3, //3 去好店  
  lat: "",
  lng: ""
})